package com.hnau.chpater9;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ActivityThreadMedia extends Activity {

	private Button btnPlay,btnStop;
	private MediaPlayer mp;
	private Thread thread;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_thread_media);
		btnPlay = (Button)super.findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				v.setEnabled(false);
				thread = new Thread(){
					public void run(){
						playBGSound();
					}
				};
				thread.start();
				
			}
		});
		btnStop  =(Button)super.findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mp !=null){
					mp.pause();
					btnPlay.setEnabled(true);
				}
			}
		});
	}
	private void playBGSound(){
		if(mp !=null){
			mp.release();
		}
		mp = MediaPlayer.create(ActivityThreadMedia.this, R.raw.beautiful);
		mp.start();
	}
	@Override
	protected void onDestroy() {
		if(mp!=null){
			mp.stop();
			mp.release();
			mp=null;
		}
		if(thread!=null){
			thread =null;
		}
		super.onDestroy();
	}
	
}
